/**
 * @author:稀饭
 * @time:上午12:00:19
 * @filename:Work.java
 */
package service;

import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import net.sf.json.JSONObject;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import util.ConnectionUtil;
import util.StringRiceUtil;
import bean.Video;
import data.Data;

public class Work_rice {
	private static ConnectionUtil connectionWork;
	// 預線程數
	private static int corePoolSize = 5;
	// 開啟的最大線程數
	private static int maximumPoolSize = 10;
	// 空閒線程存活時間
	private static long keepAliveTime = 3;
	private static ThreadPoolExecutor threadPool = null;
	private static BlockingQueue<Runnable> linkedBlockingQueue = null;

	public static void main(String[] args) {
		setThreadPool();
		connectionWork = new ConnectionUtil();
		String result = null;
		try {
			result = getContent(Data.ssologin, Data.requestProperties);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (result != null) {
			String param = getLoginParam(result);
			String cookies = getCookies(param, Data.submit,
					Data.requestProperties);
			// 建立requestProperty
			String[] requestProperties = { "Cookie: " + cookies };
			// 下载部分视频
			if (Data.select == false) {
				if(Data.courseInfo.length==0)
				{
					System.out.println("Data.courseInfo中沒有錄入數據...");
				}
				for (int i = 0; i < Data.courseInfo.length; i++) {
					String info = Data.courseInfo[i];
					download(info, requestProperties);
				}
			}
			// 下载所有视频
			else {
				LinkedBlockingQueue<String> linkedBlockingQueue = getContentInfo();
				if (!linkedBlockingQueue.isEmpty()) {
					Iterator<String> iterator = linkedBlockingQueue.iterator();
					while (iterator.hasNext()) {
						String info = iterator.next();
						download(info, requestProperties);
					}
				}
				else
				{
					System.out.println("查无课程...");
				}
			}
		}
		threadPool.shutdown();
	}

	/**
	 * @Title: download
	 * @Description: TODO
	 * @param @param info
	 * @param @param requestProperties
	 * @return void
	 */
	public static void download(String info, String[] requestProperties) {
		String name = StringRiceUtil.fixDir(info.split(",")[1]);
		String num = info.split(",")[2];
		String id = ((info.split(",")[0]).split("/")[4]).split("\\.")[0];
		for (int d = 1; d <= Integer.parseInt(num); d++) {
			String videoDownload = Data.videoDownload.replace("NUM", d + "")
					.replace("ID", id);
			Video video = getVideoUrl(videoDownload, requestProperties,
					Data.videPath + name + "/", d);
			if (video != null) {
				CreateVideo createVideo = new CreateVideo(video);
				threadPool.execute(createVideo);
			}
		}
	}

	// 開啟線程池
	public static void setThreadPool() {
		linkedBlockingQueue = new ArrayBlockingQueue<Runnable>(4);
		threadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
				keepAliveTime, TimeUnit.DAYS, linkedBlockingQueue,
				new ThreadPoolExecutor.CallerRunsPolicy());
	}

	/**
	 * @Title: getContentInfo
	 * @Description: 从指定页面获取所有教学内容的重要信息
	 * @param @return
	 * @return LinkedBlockingQueue<String>
	 */
	public static LinkedBlockingQueue<String> getContentInfo() {
		LinkedBlockingQueue<String> linkedBlockingQueue = new LinkedBlockingQueue<String>();
		connectionWork = new ConnectionUtil();
		// course课程页面信息
		String course = Data.course;
		// 页数
		int pageNum = Data.maxNum;
		String content = null;
		for (int n = 1; n <= pageNum; n++) {
			try {
				content = getContent(course + pageNum, null);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Document document = Jsoup.parse(content);
			Element element = document.select(".lesson-list").first();
			Elements elements = element.select("li");
			String result = "";
			for (int i = 0; i < elements.size(); i++) {
				Element element1 = elements.get(i).select("em").first();
				Element element2 = elements.get(i).select(".lesson-info-h2")
						.first();
				String name = element2.text();
				String time = element1.text().split("课时")[0];
				String href = element2.select("a").attr("href");
				result = href + "," + name + "," + time;
				linkedBlockingQueue.add(result);
			}
		}
		return linkedBlockingQueue;
	}

	/**
	 * @Title: download
	 * @Description: TODO
	 * @param @param htmlUrl
	 * @param @param requestProperties
	 * @return Video返回視頻對象
	 */
	public static Video getVideoUrl(String htmlUrl, String[] requestProperties,
			String path, int id) {
		String result = null;
		Video video = null;
		try {
			while (result == null)
				result = getContent(htmlUrl, requestProperties);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JSONObject jsonObject = JSONObject.fromObject(StringRiceUtil
				.replaceBlank(result.replace("null", "")));
		JSONObject jsonObject2 = jsonObject.getJSONObject("data");
		if (jsonObject2 != null) {
			String urls = null;
			String name = null;
			if (jsonObject2.get("urls") != null) {
				urls = jsonObject2.get("urls").toString();
				name = id + "、" + jsonObject2.get("title").toString() + ".mp4";
			}

			if (urls != null && name != null)
				video = new Video(name, urls, path);
		}
		return video;
	}

	/**
	 * @Title: getCookies
	 * @Description: TODO
	 * @param param
	 * @param htmlUrl
	 * @param requestProperties
	 * @return
	 */
	@SuppressWarnings("static-access")
	public static String getCookies(String param, String htmlUrl,
			String[] requestProperties) {
		String result = null;
		try {
			result = connectionWork.getCookie(param, htmlUrl);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * @Title: getContent
	 * @Description: TODO
	 * @param @param htmlUrl
	 * @param @param requestProperties
	 * @param @return
	 * @param @throws IOException
	 * @return String
	 */
	@SuppressWarnings("static-access")
	public static String getContent(String htmlUrl, String[] requestProperties)
			throws IOException {
		int time = 0;
		String result = null;
		while (result == null) {
			time++;
			result = connectionWork.sendGet(htmlUrl, requestProperties);
			if (time == 10) {
				System.out.println("网络不好，已中断...");
				break;
			}
		}
		return result;
	}

	/**
	 * @Title: getLoginParam
	 * @Description: TODO
	 * @param @param content
	 * @param @return
	 * @return String
	 */
	public static String getLoginParam(String content) {

		String result = "";
		Document document = Jsoup.parse(content);
		Element element = document.select("#login-form").first();
		Elements elements = element.select("input[type=hidden]");
		for (int i = 0; i < elements.size(); i++) {
			String value = elements.get(i).attr("value");
			String key = elements.get(i).attr("name");
			result += key + "=" + value + "&";
		}
		result = result + "uname=" + Data.username + "&password="
				+ Data.password + "&verify=";
		return result;
	}
}
